<template>
  <el-form :model="data" :rules="formRules">
    <el-form-item 
      v-for="(formItem, index) in formItems" 
      :key="index"
      :label="formItem.label"
      :prop="formItem.field"
      v-show="isShowComp(formItem)"
    >
      <component 
        :is="getCompType(formItem)" 
        v-model="data[formItem.field]"
      >
        <template v-if="isShowSlot(formItem)">
          <el-option 
            v-for="(option, ind) in formItem.options" 
            :key="ind" 
            :label="option.label"
            :value="option.value"
          ></el-option>
        </template>
      </component>
    </el-form-item>
  </el-form>
</template>

<script setup>
  import { computed } from 'vue'
  const props = defineProps({
    formItems: Array,
    data: Object,
  })
  // 校验规则
  const formRules = computed(() => {
    return props.formItems?.reduce((acc, cur) => {
      if(cur.validator) {
        acc[cur.field] = cur.validator
      }
      return acc
    }, {})
  })
  // 获取element-plus组件类型
  const getCompType = (formItem) => {
    const { type } = formItem || {}
    const mapping = {
      input: 'el-input',
      select: 'el-select',
    }
    return mapping[type]
  }
  // 是否显示formItem
  const isShowComp = (formItem) => {
    const { dependence } = formItem || {}
    if (!dependence) return true

    const { value, field } = dependence
    return props.data[field] === value
  }
  // 是否显示插槽
  const isShowSlot = (formItem) => {
    const { type } = formItem || {}
    const slotTypes = ['select']
    return slotTypes.includes(type)
  }

</script>

<style scoped>

</style>
